package com.iocup.keybastion.authentication.impl;



import com.iocup.keybastion.configuration.TokenProperties;
import com.iocup.keybastion.authentication.AbstractTokenBuilder;
import com.iocup.keybastion.authentication.AccessToken;
import com.iocup.keybastion.authentication.RefreshToken;
import com.iocup.keybastion.core.profile.UserProfile;

import java.util.Date;
import java.util.UUID;

/**
 * 默认的token构建器，如果需要生成jwt方式token，可以参照此实现类
 *
 * @author xyjxust
 * @create 2022/3/4 15:32
 **/
public class DefaultTokenBuilder extends AbstractTokenBuilder {


    public DefaultTokenBuilder(TokenProperties tokenProperties) {
        super(tokenProperties);
    }


    @Override
    public AccessToken build(UserProfile userProfile) {
        return build(userProfile, createRefreshToken(userProfile));
    }

    @Override
    public AccessToken build(UserProfile userProfile, RefreshToken refreshToken) {
        DefaultAccessToken oAuth2AccessToken = DefaultAccessToken.build(UUID.randomUUID().toString());
        oAuth2AccessToken.refreshToken(refreshToken);
        int validitySeconds = getTokenValiditySeconds(userProfile.getDevice());
        if (validitySeconds > 0) {
            oAuth2AccessToken.setExpireTime(new Date(System.currentTimeMillis() + (long) validitySeconds * 1000L));
        }
        return oAuth2AccessToken;
    }

    @Override
    public AccessToken build(AccessToken accessToken, UserProfile userProfile) {
        DefaultAccessToken oAuth2AccessToken = DefaultAccessToken.build(accessToken.getAccessToken());
        int validitySeconds = getTokenValiditySeconds(userProfile.getDevice());
        if (validitySeconds > 0) {
            oAuth2AccessToken.setExpireTime(new Date(System.currentTimeMillis() + (long) validitySeconds * 1000L));
        }
        return oAuth2AccessToken;
    }

    private RefreshToken createRefreshToken(UserProfile userProfile) {
        if (this.tokenProperties.isRefreshToken()) {
            RefreshToken refreshToken = DefaultRefreshToken.builder().token(UUID.randomUUID().toString()).build();
            int validitySeconds = getRefreshTokenValiditySeconds(userProfile.getDevice());
            if (validitySeconds > 0) {
                refreshToken.setExpiration(new Date(System.currentTimeMillis() + (long) validitySeconds * 1000L));
            }
            return refreshToken;
        }
        return null;
    }


}
